<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('合同预算、预测、实际回款管理')" />
	<th:block th:include="include :: bootstrap-editable-css" />
	<th:block th:include="include :: select2-css" />
</head>
<body class="gray-bg">
     <div class="container-div">
		 <div class="tabs-container">
			 <ul class="nav nav-tabs">
				 <li class="active"><a data-toggle="tab" href="#tab-1" aria-expanded="true" onclick="initBudget()">预算管理</a>
				 </li>
				 <li class=""><a data-toggle="tab" href="#tab-2" aria-expanded="false" onclick="initPredict()">预测管理</a>
				 </li>
				 <li class=""><a data-toggle="tab" href="#tab-3" aria-expanded="false" onclick="initActual()">实际回款管理</a>
				 </li>
			 </ul>
			 <div class="tab-content">
				 <div id="tab-1" class="tab-pane active">
					 <div class="btn-group-sm" id="toolbar" role="group">
						 <a class="btn btn-primary" onclick="addBudget()">
							 <i class="fa button"></i> 添加预算
						 </a>
						 <div style="float:right;margin-left: 10px;">
							 <select id="budgetStage"></select>
						 </div>
					 </div>
					 <div class="row">
						 <div class="col-sm-12 select-table table-striped">
							 <table id="bootstrap-table"></table>
						 </div>
					 </div>
				 </div>

				 <div id="tab-2" class="tab-pane">
					 <div class="btn-group-sm" id="toolbar1" role="group">
						 <a class="btn btn-primary" onclick="addPredict()">
							 <i class="fa button"></i> 添加预测
						 </a>
						 <div style="float:right;margin-left: 10px;">
							 <select id="predictStage"></select>
						 </div>
					 </div>
					 <div class="row">
						 <div class="col-sm-12 select-table table-striped">
							 <table id="bootstrap-table1"></table>
						 </div>
					 </div>
				 </div>

				 <div id="tab-3" class="tab-pane">
					 <div class="btn-group-sm" id="toolbar2" role="group">
						 <a class="btn btn-primary" onclick="addActual()">
							 <i class="fa button"></i> 添加实际回款
						 </a>
						 <div style="float:right;margin-left: 10px;">
							 <select id="actualStage"></select>
						 </div>
					 </div>
					 <div class="row">
						 <div class="col-sm-12 select-table table-striped">
							 <table id="bootstrap-table2"></table>
						 </div>
					 </div>
				 </div>

				 <span th:text="'合同金额：' + ${alpContractDetail.contractMoney} + ';' "></span><br/>
				 <span th:text="'签订合同时间：' + ${contractSignTime} + ';' "></span><br/>
				 <span th:text="'初验时间：' + ${firstAcceptanceTime} + ';' "></span><br/>
				 <span th:text="'终验时间：' + ${finialAcceptanceTime} + ';' "></span><br/>
				 <span th:text="'已回款金额：' + ${alpContractDetail.notReceivedMoney} + ';' "></span><br/>
				 <span th:text="'未回款金额：' + ${alpContractDetail.notReceivedMoney} + ';' "></span><br/>
				 <span th:text="'回款条件：' + ${alpContractDetail.paymentCondition} + ';' "></span><br/>
			 </div>
		 </div>
	</div>
	
	<th:block th:include="include :: footer" />
	<th:block th:include="include :: bootstrap-table-editable-js" />
	<th:block th:include="include :: select2-js" />
    <script th:inline="javascript">
        var prefix = ctx + "system/budget";
        var prefixSystem = ctx + "system";
        var alpContractDetail = [[${alpContractDetail}]];
        var stageList = [[${stageList}]];
        var newRow;
		var newRowCount = 0;
        $(function() {
            console.log(moment(alpContractDetail.contractSignTime).format('MMMM Do YYYY, h:mm:ss a'));
			initBudget();
			var stageData = new Array();
			var placeHolder = new Object();
            placeHolder.id = -1;
            placeHolder.text = '请选择合同阶段';
			stageData.push(placeHolder);
			for(let i = 0; i < stageList.length; i++){
			    var stageObj = new Object();
			    stageObj.id = stageList[i].stageId;
			    stageObj.text = stageList[i].stageName;
			    stageData.push(stageObj);
			}
            $('#budgetStage').select2({
                data: stageData
			});
			$('#predictStage').select2({
                data: stageData
            });
			$('#actualStage').select2({
                data: stageData
            });
			debugger
			$("#formateddate").val(77777777777777777777)
            $("#formateddate").val(moment(alpContractDetail.contractSignTime).format('MMMM Do YYYY, h:mm:ss a'))
            // moment(alpContractDetail.contractSignTime).format('MMMM Do YYYY, h:mm:ss a')


        });


        function initBudget(){
            newRow = {};
            newRowCount = 0;
            $('#bootstrap-table').bootstrapTable('destroy');
            var options = {
                url: prefix + "/listBudgetTable/"+ alpContractDetail.contractId,
				removeUrl: prefix + "/remove/{id}",
				modalName: '预算',
                showSearch: false,
                showRefresh: true,
                showToggle: false,
                showColumns: false,
                showPageGo: true,
                showFooter: true,
				pageSize: 5,
                sortName: 'updatedTime',
                sortOrder: 'desc',
                onEditableSave: onEditableSaveBudget,
                columns: [
				{
					field : 'id',
					title : '主键id',
					visible: false
				},
				{
					field : 'contractId',
					title : '合同id',
                    visible: false
				},
				{
					field : 'stageId',
					title : '合同阶段id',
                    visible: false
				},
				{
					field : 'alpContractStage.stageNo',
					title : '阶段序号'
				},
				{
					field : 'alpContractStage.stageName',
					title : '阶段名称'
                    // formatter: function(value, row, index){
					 //    var colors = ['#00FF00','#0000FF','#FF0000','#FFFF00'];
                    //     for(let i = 0; i < stageList.length; i++){
                    //         if(value == stageList[i].stageName){
                    //             let j = i % 4;
						// 		return '<span style="color:' + colors[j] + '">'+value+'</span>';
						// 	}
                    //     }
                    // }
				},
				{
					field : 'budgetMoney',
					title : '预算收款金额(元)',
					editable: {
                        type: 'text',
                        title: '预算收款金额',
                        validate: function (v) {
                            if (isNaN(v)) return '金额必须是数字';
                        }
                    },
                    footerFormatter: function (value) {
					    console.log(value);
                        var sumBalance = 0;
                        for (var i in value) {
                            sumBalance += parseFloat(value[i].budgetMoney);
                        }
                        return "预算总金额：" + sumBalance;
                    }
				},
				{
					field : 'budgetTime',
					title : '预算收款时间',
                    editable: {
                        type: 'date',
                        clear: false,
                        placement: 'left',
                        title: '请选择日期:'
                    },
                    formatter: function(value, row, index){
                        return changeDateFormat(value);
                    }
				},
				{
					field : 'isAdd',
					title : '是否新增',
					visible: false,
                    formatter: function(value, row, index){
					    if(value == "是"){
					        return value;
						} else {
					        return "否";
						}
					}
				},
				{
					title: '操作',
					align: 'center',
					formatter: function(value, row, index) {
						var actions = [];
						if(row.isAdd == '是'){
						    newRow = row;
                            actions.push('<a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="insertNewBudget()"><i class="fa fa-check"></i>提交</a>&nbsp;');
                            actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="initBudget()"><i class="fa fa-remove"></i>删除</a>');
						} else {
                            actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.id + '\')"><i class="fa fa-remove"></i>删除</a>');
						}
						return actions.join('');
					}
				}]
            };
            $.table.init(options);
		}

        function initPredict(){
            newRow = {};
            newRowCount = 0;
            $('#bootstrap-table1').bootstrapTable('destroy');
            var options = {
                id: "bootstrap-table1",
                toolbar: "toolbar1",
                url: prefixSystem + "/predict/listPredictTable/"+ alpContractDetail.contractId,
                removeUrl: prefixSystem + "/predict/remove/{id}",
                modalName: '预测',
                // createUrl: prefix + "/add",
                // updateUrl: prefix + "/edit/{id}",
                showSearch: false,
                showRefresh: true,
                showToggle: false,
                showColumns: false,
                showPageGo: true,
				showFooter: true,
                pageSize: 5,
                sortName: 'updatedTime',
                sortOrder: 'desc',
                onEditableSave: onEditableSavePredict,
                columns: [
				{
					field : 'id',
					title : '主键id',
					visible: false
				},
				{
					field : 'contractId',
					title : '合同id',
					visible: false
				},
				{
					field : 'stageId',
					title : '合同阶段id',
					visible: false
				},
				{
					field : 'alpContractStage.stageNo',
					title : '阶段序号'
				},
				{
					field : 'alpContractStage.stageName',
					title : '阶段名称'
				},
				{
					field : 'predictMoney',
					title : '预测收款金额',
                    editable: {
                        type: 'text',
                        title: '预测收款金额(元)',
                        validate: function (v) {
                            if (isNaN(v)) return '金额必须是数字';
                        }
                    },
                    footerFormatter: function (value) {
                        console.log(value);
                        var sumBalance = 0;
                        for (var i in value) {
                            sumBalance += parseFloat(value[i].predictMoney);
                        }
                        return "预测总金额：" + sumBalance;
                    }
				},
				{
					field : 'predictTime',
					title : '预测收款时间',
                    editable: {
                        type: 'date',
                        clear: false,
                        placement: 'left',
                        title: '请选择日期:'
                    },
                    formatter: function(value, row, index){
                        return changeDateFormat(value);
                    }
				},
				{
					field : 'isAdd',
					title : '是否新增',
					formatter: function(value, row, index){
						if(value == "是"){
							return value;
						} else {
							return "否";
						}
					}
				},
				{
					title: '操作',
					align: 'center',
					formatter: function(value, row, index) {
						var actions = [];
						if(row.isAdd == '是'){
							newRow = row;
							actions.push('<a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="insertNewPredict()"><i class="fa fa-check"></i>提交</a>&nbsp;');
							actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="initPredict()"><i class="fa fa-remove"></i>删除</a>');
						} else {
							actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.id + '\')"><i class="fa fa-remove"></i>删除</a>');
						}
						return actions.join('');
					}
				}]
            };
            $.table.init(options);
		}

        function initActual(){
            newRow = {};
            newRowCount = 0;
            $('#bootstrap-table2').bootstrapTable('destroy');
            var options = {
                id: "bootstrap-table2",
                toolbar: "toolbar2",
                url: prefixSystem + "/actual/listActualTable/"+ alpContractDetail.contractId,
                removeUrl: prefixSystem + "/actual/remove/{id}",
                modalName: '实际回款',
                // createUrl: prefix + "/add",
                // removeUrl: prefix + "/remove",
                // updateUrl: prefix + "/edit/{id}",
                showSearch: false,
                showRefresh: true,
                showToggle: false,
                showColumns: false,
                showPageGo: true,
				showFooter: true,
                pageSize: 5,
				sortName: 'updatedTime',
				sortOrder: 'desc',
                onEditableSave: onEditableSaveActual,
                columns: [
				{
					field : 'id',
					title : '主键id',
					visible: false
				},
				{
					field : 'contractId',
					title : '合同id',
					visible: false
				},
				{
					field : 'stageId',
					title : '合同阶段id',
					visible: false
				},
				{
					field : 'alpContractStage.stageNo',
					title : '阶段序号'
				},
				{
					field : 'alpContractStage.stageName',
					title : '阶段名称'
				},
				{
					field : 'actualMoney',
					title : '实际收款金额(元)',
                    editable: {
                        type: 'text',
                        title: '实际收款金额',
                        validate: function (v) {
                            if (isNaN(v)) return '金额必须是数字';
                        }
                    },
                    footerFormatter: function (value) {
                        console.log(value);
                        var sumBalance = 0;
                        for (var i in value) {
                            sumBalance += parseFloat(value[i].actualMoney);
                        }
                        return "回款总金额：" + sumBalance;
                    }
				},
				{
					field : 'actualTime',
					title : '实际收款时间',
                    editable: {
                        type: 'date',
                        clear: false,
                        placement: 'left',
                        title: '请选择日期:'
                    },
                    formatter: function(value, row, index){
                        return changeDateFormat(value);
                    }
				},
				{
					field : 'isAdd',
					title : '是否新增',
					formatter: function(value, row, index){
						if(value == "是"){
							return value;
						} else {
							return "否";
						}
					}
				},
				{
					title: '操作',
					align: 'center',
					formatter: function(value, row, index) {
						var actions = [];
						if(row.isAdd == '是'){
							newRow = row;
							actions.push('<a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="insertNewActual()"><i class="fa fa-check"></i>提交</a>&nbsp;');
							actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="initActual()"><i class="fa fa-remove"></i>删除</a>');
						} else {
							actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.id + '\')"><i class="fa fa-remove"></i>删除</a>');
						}
						return actions.join('');
					}
				}]
            };
            $.table.init(options);
        }

        function addBudget(){
            var tableData = $('#bootstrap-table').bootstrapTable('getData');
            var stageId = $('#budgetStage option:checked').val();
            var stageName = $('#budgetStage option:checked').text();
            if(newRowCount != 0) {
                $.modal.alert("请先提交未保存的记录");
            } else {
                if(stageId != -1) {
                    $('#bootstrap-table').bootstrapTable('insertRow', {
                        index: 0,
                        row: {
							contractId : alpContractDetail.contractId,
                            stageId: stageId,
                            alpContractStage: {'stageNo': stageId, 'stageName': stageName},
                            budgetMoney: 0,
                            budgetTime: getNowFormatDate(),
                            isAdd: '是'
                        }
                    });
                    newRowCount += 1;
                } else {
                    $.modal.alert("请先选择合同阶段");
                }
            }
        }

        function onEditableSaveBudget (field, row, oldValue, $el) {
			if (row.isAdd != '是') {
				if(newRowCount != 0) {
					$.modal.alert("请先提交未保存的记录");
				} else {
					$.ajax({
						type: "post",
						url: prefix + "/editOneLine/" + row.id + "/" + row.budgetMoney + "/" + row.budgetTime,
						beforeSend: function () {
							$.modal.loading("正在处理中，请稍后...");
						},
						success: function (result) {
							if (result.code == web_status.SUCCESS) {
								$.modal.msgSuccess(result.msg);
								$('#bootstrap-table').bootstrapTable('refresh');
							} else if (result.code == web_status.WARNING) {
								$.modal.alertWarning(result.msg)
							} else {
								$.modal.alertError(result.msg);
							}
							$.modal.closeLoading();
						}
					});
                }
            }
        }

        function insertNewBudget() {
            delete newRow.alpContractStage ;
			$.ajax({
                type: "post",
                url: prefix + "/add",
				data: newRow,
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍后...");
                },
                success: function (result) {
                    if (result.code == web_status.SUCCESS) {
                        $.modal.msgSuccess(result.msg);
                    } else if (result.code == web_status.WARNING) {
                        $.modal.alertWarning(result.msg)
                    }  else {
                        $.modal.alertError(result.msg);
                    }
                    newRow = {};
                    newRowCount = 0;
                    $.modal.closeLoading();
                    initBudget();
                }
			});
        }

        function addPredict(){
            var tableData = $('#bootstrap-table1').bootstrapTable('getData');
            var stageId = $('#predictStage option:checked').val();
            var stageName = $('#predictStage option:checked').text();
            if(newRowCount != 0) {
                $.modal.alert("请先提交未保存的记录");
            } else {
                if(stageId != -1) {
                    $('#bootstrap-table1').bootstrapTable('insertRow', {
                        index: 0,
                        row: {
                            contractId : alpContractDetail.contractId,
                            stageId: stageId,
                            alpContractStage: {'stageNo': stageId, 'stageName': stageName},
                            predictMoney: 0,
                            predictTime: getNowFormatDate(),
                            isAdd: '是'
                        }
                    });
                    newRowCount += 1;
                } else {
                    $.modal.alert("请先选择合同阶段");
                }
            }
        }

        function onEditableSavePredict (field, row, oldValue, $el) {
            if (row.isAdd != '是') {
                if (newRowCount != 0) {
                    $.modal.alert("请先提交未保存的记录");
                } else {
                    $.ajax({
                        type: "post",
                        url: prefixSystem + "/predict/editOneLine/" + row.id + "/" + row.predictMoney + "/" + row.predictTime,
                        beforeSend: function () {
                            $.modal.loading("正在处理中，请稍后...");
                        },
                        success: function (result) {
                            if (result.code == web_status.SUCCESS) {
                                $.modal.msgSuccess(result.msg);
                                $('#bootstrap-table1').bootstrapTable('refresh');
                            } else if (result.code == web_status.WARNING) {
                                $.modal.alertWarning(result.msg)
                            } else {
                                $.modal.alertError(result.msg);
                            }
                            $.modal.closeLoading();
                        }
                    });
                }
            }
        }

        function insertNewPredict() {
            delete newRow.alpContractStage ;
            $.ajax({
                type: "post",
                url: prefixSystem + "/predict/add",
                data: newRow,
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍后...");
                },
                success: function (result) {
                    if (result.code == web_status.SUCCESS) {
                        $.modal.msgSuccess(result.msg);
                    } else if (result.code == web_status.WARNING) {
                        $.modal.alertWarning(result.msg)
                    }  else {
                        $.modal.alertError(result.msg);
                    }
                    newRow = {};
                    newRowCount = 0;
                    $.modal.closeLoading();
                    initPredict();
                }
            });
        }

        function addActual(){
            var tableData = $('#bootstrap-table2').bootstrapTable('getData');
            var stageId = $('#actualStage option:checked').val();
            var stageName = $('#actualStage option:checked').text();
            if(newRowCount != 0) {
                $.modal.alert("请先提交未保存的记录");
            } else {
                if(stageId != -1) {
                    $('#bootstrap-table2').bootstrapTable('insertRow', {
                        index: 0,
                        row: {
                            contractId : alpContractDetail.contractId,
                            stageId: stageId,
                            alpContractStage: {'stageNo': stageId, 'stageName': stageName},
                            actualMoney: 0,
                            actualTime: getNowFormatDate(),
                            isAdd: '是'
                        }
                    });
                    newRowCount += 1;
                } else {
                    $.modal.alert("请先选择合同阶段");
                }
            }
        }

        function onEditableSaveActual (field, row, oldValue, $el) {
            if (row.isAdd != '是') {
                if (newRowCount != 0) {
                    $.modal.alert("请先提交未保存的记录");
                } else {
                    $.ajax({
                        type: "post",
                        url: prefixSystem + "/actual/editOneLine/" + row.id + "/" + row.actualMoney + "/" + row.actualTime,
                        beforeSend: function () {
                            $.modal.loading("正在处理中，请稍后...");
                        },
                        success: function (result) {
                            if (result.code == web_status.SUCCESS) {
                                $.modal.msgSuccess(result.msg);
                                $('#bootstrap-table2').bootstrapTable('refresh');
                            } else if (result.code == web_status.WARNING) {
                                $.modal.alertWarning(result.msg)
                            } else {
                                $.modal.alertError(result.msg);
                            }
                            $.modal.closeLoading();
                        }
                    });
                }
            }
        }

        function insertNewActual() {
            delete newRow.alpContractStage ;
            $.ajax({
                type: "post",
                url: prefixSystem + "/actual/add",
                data: newRow,
                beforeSend: function () {
                    $.modal.loading("正在处理中，请稍后...");
                },
                success: function (result) {
                    if (result.code == web_status.SUCCESS) {
                        $.modal.msgSuccess(result.msg);
                    } else if (result.code == web_status.WARNING) {
                        $.modal.alertWarning(result.msg)
                    }  else {
                        $.modal.alertError(result.msg);
                    }
                    newRow = {};
                    newRowCount = 0;
                    $.modal.closeLoading();
                    initActual();
                }
            });
        }



        function changeDateFormat(cellval){
            var dateVal = cellval + "";
            if (cellval != null) {
                dateVal = dateVal.split(' ');
                return dateVal[0];
            } else {
                return '-';
            }
        }

        function getNowFormatDate() {
            var date = new Date();
            var seperator1 = "-";
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            var currentdate = year + seperator1 + month + seperator1 + strDate;
            return currentdate;
        }
    </script>
</body>
</html>